import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_1911/bean/bean.dart';
import 'package:flutter_1911/dao/home_dao.dart';
import 'package:flutter_1911/model/common_model.dart';
import 'package:flutter_1911/model/config_model.dart';
import 'package:flutter_1911/model/grid_model.dart';
import 'package:flutter_1911/model/home_model.dart';
import 'package:flutter_1911/model/sales_model.dart';
import 'package:flutter_1911/pages/classification_page.dart';
import 'package:flutter_1911/until/nav_until.dart';
import 'package:flutter_1911/widget/SearchBar.dart';
import 'package:flutter_1911/widget/grid.dart';
import 'package:flutter_1911/widget/sales.dart';
import 'package:flutter_1911/widget/sub.dart';
import 'package:flutter_1911/widget/webview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
// import 'package:flutter_1911/widget/search_bar.dart';
import '../service/service.dart';

const APPBAR_SCROLL = 100;
const SEARCH_BAR_TXT = '网红打卡地 景点 酒店 美食';
//  进行页面加载
bool _loding =false;
double appBarAlpha = 0;
class HomePage extends StatefulWidget {
  static ConfigModel? configModel;
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    // getHomeBanner().then((value) => print(value));
    super.initState();
    loadData();
  }

  double appBarAlpha = 0;

  String resultString = "";
  List<CommonModel> local = [];
  List<CommonModel> subList = [];
  GridModel? gridNavModel;
  SalesModel? salesModel;

  _onScroll(Offset) {
    double alpha = Offset / APPBAR_SCROLL;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  //导航栏请求数据
  loadData() async {
    try {
      HomeModel model = await HomeDao.homeRequest();
      setState(() {
        local = model.localNavList;
        gridNavModel = model.gridNav;
        subList = model.subNavList;
        salesModel = model.salesBox;
      });
    } catch (e) {
      print(e);
    }
  }
  _jumtosearch(BuildContext context) {

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff2f2f2),
        body: Stack(
          children: [
            MediaQuery.removePadding(
                //删除顶部的padding
                removeTop: true,
                context: context,
                child: NotificationListener(
                  onNotification: (Scroll) {
                    if (Scroll is ScrollUpdateNotification &&
                        Scroll.depth == 0) {
                      //滚动且是列表滚动的时候
                      _onScroll(Scroll.metrics.pixels);
                    }
                    return true;
                  },
                  child: ListView(
                    children: [
                      //轮播图
                      FutureBuilder(
                        future: request('homePage',null),
                        builder: (context, val) {
                          if (val.hasData) {
                            List<BannerList> homeBannerBeanList =
                                Bean.fromJson(val.data).bannerList!;
                            return MySwiper(
                                homeBannerBeanList: homeBannerBeanList);
                          } else {
                            return const Text('加载中...');
                          }
                        },
                      ),

                      FutureBuilder(
                          future: request('homePage', null),
                          builder: (context, val) {
                            if (val.hasData) {
                              List<LocalNavList> homeNavigatorList =
                              Bean.fromJson(val.data).localNavList!;
                              return HomeNavigator(navigatorList: homeNavigatorList);
                            } else {
                              return const Center(
                                child: Text('加载中...'),
                              );
                            }
                          }),
                      //网格布局
                      Grid(gridNavModel: gridNavModel!),
                      //底部卡片入口
                      Sub(subList: subList),

                      Sales(sales: salesModel!),
                      //列表高度
                      const SizedBox(
                        height: 10,
                      )
                    ],
                  ),
                )),

            Opacity(
              opacity: appBarAlpha,
              child: Container(
                height: 80,
                decoration: BoxDecoration(color: Colors.black12),
                // child: _appBar,
              ),
            ),
            _appBar,
          ],
        ));
  }
  Widget get  _appBar {
    return Column(
      children:<Widget> [
        Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                //AppBar渐变遮罩背景
                colors: [Color(0x96000000),Colors.transparent],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              )
          ),
          child: Container(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 20),
            height: 70.0,
            decoration: BoxDecoration(
              //根据透明度设置图片的颜色
              color: Color.fromRGBO((appBarAlpha*255).toInt(), 255, 255, 255),

            ),
            child:SearchBar(
              searchBartype: appBarAlpha>0.2? SearchBarType.homeLight :SearchBarType.home,
              inputBoxClick: (){
                Navigator.push(context, MaterialPageRoute(
                    builder: (BuildContext context) => ClassificationPage()
                ));
              },
              speakClick: _jumpToSeak,
              defaultText: SEARCH_BAR_TXT,
              leftButtonClick: (){},
            ) ,
          ),
        ),
        Container(
          //设置透明度
          height: appBarAlpha>0.2 ? 0.5 :0,
          decoration: const BoxDecoration(
            boxShadow: [BoxShadow(color: Colors.black12,blurRadius: 0.5)
            ],
          ),
        )
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}

_jumpToSeak() {
}
//轮播图控件
class MySwiper extends StatelessWidget {
  final List<BannerList> homeBannerBeanList;

  const MySwiper({Key? key, required this.homeBannerBeanList})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: ScreenUtil().setHeight(330),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        onTap: (index){
          NavigatorUtil.push(
              context,
              HiWebView(
                url: homeBannerBeanList[index].url,
              )
          );
        },
        itemCount: homeBannerBeanList.length,
        itemBuilder: (context, index) {
          return Image.network(
            homeBannerBeanList[index].icon!,
            fit: BoxFit.fill, //代表图片全屏拉伸
          );
        },
        pagination: const SwiperPagination(), //控制轮播图的小圆点
        autoplay: true, //设置是否自动轮播

      ),
    );
  }
}

//导航栏控件
class HomeNavigator extends StatelessWidget {
  final List<LocalNavList> navigatorList;

  const HomeNavigator({Key? key, required this.navigatorList})
      : super(key: key);

  //girdViewItem的布局
  Widget _girdViewItemUI(context, LocalNavList item) {
    return InkWell(
      onTap: () {
        NavigatorUtil.push(
            context,
            HiWebView(
              url: item.url,
              statusBarColor: item.statusBarColor,
              hideAppBar: item.hideAppBar,
            ));
      },
      child: Column(
        children: [
          Image.network(
            '${item.icon}',
            width: ScreenUtil().setWidth(80),
          ),
          Text('${item.title}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(150),
      padding: const EdgeInsets.all(3.0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: const EdgeInsets.all(4.0),
        children: navigatorList.map((it) {
          return _girdViewItemUI(context, it);
        }).toList(), //拿到数据集合后,将它迭代(遍历),把其中的每一个数值赋值给item,再形成一个item的集合
      ),
    );
  }
}
